﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MockSchoolManagement.DataRepositories;
using MockSchoolManagement.Models;
using MockSchoolManagement.ViewModels;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MockSchoolManagement.Controllers
{
    [Authorize]//不允许匿名访问
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment _webHostEnvironment;
        private readonly ILogger<HomeController> _logger;
        //使用构造函数注入的方式注入IStudentRepository
        public HomeController(IStudentRepository studentRepository, IWebHostEnvironment webHostEnvironment,ILogger<HomeController> logger)
        {
            _studentRepository = studentRepository;
            _webHostEnvironment = webHostEnvironment;
            _logger = logger;
        }

         
        //返回学生的名字
        public ViewResult Index()
        {

            //var _studentRepository = new MockStudentRepository();
            //var a = _studentRepository.GetStudent(1);
            //HomeDetailsViewModel viewModel = new HomeDetailsViewModel() { PageTitle = "学生详情", Student =a};
            //ViewBag.PageTitle = "学生详情";
            ViewBag.Title = "学生列表";
            // ViewBag.Student=a;
            var mode = _studentRepository.GetAllStudents();
            return View(mode);
        }
        [Route("home/Details/{id?}")]
        [AllowAnonymous]//允许匿名访问
        public ViewResult Details(int id)
        {
            _logger.LogTrace("Trace(跟踪)Log");
            _logger.LogDebug("Debug(调试)Log");
            _logger.LogInformation("信息(Information)Log");
            _logger.LogWarning("警告(Warning)Log");
            _logger.LogError("错误(Error)Log");
            _logger.LogCritical("严重(Critical)Log");
            Student model=_studentRepository.GetStudent(id);
            //使用ViewData将PageTitle和Student模型传递给View
            //ViewData["PageTitle"] = "Student Detalils";
           // ViewData["Student"] = model;
            return View(model);
        }
        [HttpGet]
        public ViewResult Edit(int id)
        {
            Student student = _studentRepository.GetStudent(id);
            ViewBag.Title = "编辑学生信息";
            if (student==null)
            {
                Response.StatusCode = 404;
                return View("StudentNotFound",id);
            }
            StudentEditViewModel viewModel = new StudentEditViewModel()
            {
                Id = student.Id,
                Name = student.Name,
                Email = student.Email,
                Major = student.Major,
                ExistingPhotoPath=student.PhotePath
            };
            return View(viewModel);
        }
        [HttpPost]
        public IActionResult Edit(StudentEditViewModel studentEditViewModel)
        {
            if (ModelState.IsValid)
            {
                var student = _studentRepository.GetStudent(studentEditViewModel.Id);
                student.Name = studentEditViewModel.Name;
                student.Email = studentEditViewModel.Email;
                student.Major = studentEditViewModel.Major;
                //判断是有图片如果有就删除
                if (student.PhotePath.Count()>0)
                {
                    if (studentEditViewModel.ExistingPhotoPath != null)
                    {
                        string filePath = Path.Combine(_webHostEnvironment.WebRootPath, "images", "avatars", "one", studentEditViewModel.ExistingPhotoPath);
                        System.IO.File.Delete(filePath);
                    }
                    student.PhotePath = ProcessUploadedFile(studentEditViewModel);
                }
                var updatestudent = _studentRepository.Update(student);
                
                return RedirectToAction("Index");

            }
            return View(studentEditViewModel);
        }
        [HttpGet]
        public ViewResult Create()
        {
            
            ViewBag.Title = "创建";
            return View();
        }
        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = null;
                if (model.Photos != null&&model.Photos.Count>0)
                {
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + model.Photos;
                    //循环每个选定的文件
                    foreach (IFormFile photo in model.Photos)
                    {
                        //必须将图片文件上传到wwwroot的images/avatars文件夹中而要获取wwwroot文件夹的路径
                        //我们需要注入Asp.Net Core提供的WebHostEnvironment服务
                        //通过WebHostEnvironment服务获取wwwroot文件夹的路径  //后面“，”可以无限下级文件夹
                        string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images", "avatars","one");
                        //为了确保文件名是唯一的，我们在文件名后附加了一个新的Guid值和一个下划线
                        uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                        string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                        //使用IFormFile接口提供的CopyTo()方法将文件复制到wwwroot/images文件夹
                        photo.CopyTo(new FileStream(filePath, FileMode.Create));
                    }
                }

                Student newstudent = new Student
                {
                    Name = model.Name,
                    Email = model.Email,
                    Major = model.Major,
                    PhotePath = uniqueFileName
                };
                _studentRepository.Add(newstudent);
                ViewBag.Title = "创建";

                //调用Details方法并传对应的参数
                return RedirectToAction("Details", new { id = newstudent.Id });
            }
            return View();
           
        }
        public IActionResult Delete(int id)
        {
            var isok = _studentRepository.Delete(id);
            return View();
        }
        public IActionResult codeCu()
        {
            throw new Exception("抛出500异常");
            
        }
        private  string ProcessUploadedFile(StudentEditViewModel model)
        {
            string uniqueFileName=null;
            if (model.Photos.Count()>0)
            {
                foreach (var photo in model.Photos)
                {
                    string uploadsFolder = Path.Combine(_webHostEnvironment.WebRootPath, "images", "avatars", "one");
                    uniqueFileName=Guid.NewGuid().ToString() + "_" + photo.FileName;
                    var filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    using(var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        photo.CopyTo(fileStream);
                    }
                }
            }
            return uniqueFileName;
        }
    }
}
